<template>
  <div class="add-menu-container">
    <div class="header">
      <el-button icon="el-icon-arrow-left" @click="handleBack">返回</el-button>
      <span class="title">{{ isEdit ? '修改菜品' : '添加菜品' }}</span>
    </div>

    <div class="form-container">
      <el-form ref="dishForm" :model="form" :rules="rules" label-width="120px">
        <!-- 第一行：菜品名称和菜品分类 -->
        <div class="form-row">
          <el-form-item label="菜品名称" prop="name" class="form-item">
            <el-input
              v-model="form.name"
              placeholder="请填写菜品名称 *"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="菜品分类" prop="categoryId" class="form-item">
            <el-select
              v-model="form.categoryId"
              placeholder="请选择菜品分类 *"
              style="width: 100%"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 第二行：菜品价格 -->
        <div class="form-row">
          <el-form-item label="菜品价格" prop="price" class="form-item">
            <el-input-number
              v-model="form.price"
              placeholder="请设置菜品价格 *"
              :min="0"
              :precision="2"
              :step="1"
              style="width: 100%"
            />
            <span class="price-unit">元</span>
          </el-form-item>
        </div>

        <!-- 口味做法配置 -->
        <div class="flavor-section">
          <div class="section-title">
            <span>口味做法配置：</span>
          </div>

          <!-- 已添加的口味项 -->
          <div v-for="(flavor, index) in form.flavors" :key="index" class="flavor-item">
            <div class="flavor-row">
              <!-- 口味名选择器 -->
              <el-select
                v-model="flavor.name"
                placeholder="请选择口味名"
                style="width: 200px; margin-right: 16px;"
                filterable
                @change="onFlavorNameChange(index)"
              >
                <el-option
                  v-for="option in availableFlavorOptions"
                  :key="option.name"
                  :label="option.name"
                  :value="option.name"
                />
              </el-select>

              <!-- 口味标签 -->
              <el-tag
                v-for="(tag, tagIndex) in flavor.tags"
                :key="tagIndex"
                closable
                style="margin-right: 8px;"
                @close="removeFlavorTag(index, tagIndex)"
              >
                {{ tag }}
              </el-tag>

              <!-- 添加标签输入框 -->
              <el-input
                v-model="flavor.tagInput"
                placeholder="请输入标签并回车添加"
                style="width: 200px; margin-right: 16px;"
                @keyup.enter.native="addFlavorTag(index)"
              />

              <!-- 删除口味按钮 -->
              <el-button
                v-if="form.flavors.length > 1"
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeFlavor(index)"
              />
            </div>
          </div>

          <!-- 添加口味按钮 -->
          <el-button
            type="primary"
            icon="el-icon-plus"
            class="add-flavor-btn"
            @click="addFlavor"
          >
            添加口味
          </el-button>
        </div>

        <!-- 菜品图片 -->
        <div class="image-section">
          <div class="section-title">
            <span>菜品图片：</span>
          </div>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="handleImageUpload"
          >
            <img v-if="form.image" :src="getImageUrl(form.image)" class="avatar">
            <div v-else class="avatar-uploader-icon">
              <i class="el-icon-plus" />
              <div>上传图片</div>
            </div>
          </el-upload>
        </div>

        <!-- 菜品描述 -->
        <div class="description-section">
          <el-form-item label="菜品描述：" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="菜品描述，最长200字"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSave">
            {{ isEdit ? '保存' : '保存' }}
          </el-button>
          <el-button
            v-if="!isEdit"
            type="primary"
            :loading="loading"
            @click="handleSaveAndContinue"
          >
            保存并继续添加菜品
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { addDish, updateDish, getDishById, getAllCategories, uploadFile } from '@/api/menu'
import { FLAVOR_OPTIONS } from './option.vue'

export default {
  name: 'AddMenu',
  data() {
    return {
      isEdit: false,
      dishId: null,
      categories: [],
      loading: false,
      form: {
        name: '',
        categoryId: '',
        price: null,
        description: '',
        image: '',
        code: '',
        flavors: [{ name: '', tags: [], tagInput: '' }] // 初始空的口味配置
      },
      rules: {
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' },
          { min: 1, max: 20, message: '菜品名称长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' },
          { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 可用的口味选项，过滤掉已选择的口味名
    availableFlavorOptions() {
      const selectedNames = this.form.flavors.map(flavor => flavor.name).filter(name => name)
      return FLAVOR_OPTIONS.filter(option => !selectedNames.includes(option.name))
    }
  },
  created() {
    this.initPage()
    this.loadCategories()
  },
  methods: {
    initPage() {
      if (this.$route.query.id) {
        this.isEdit = true
        this.dishId = this.$route.query.id
        this.loadDishDetail()
      }
      this.setDocumentTitle()
    },
    setDocumentTitle() {
      const title = this.isEdit ? '修改菜品' : '添加菜品'
      document.title = title
      // 同时更新路由的meta.title
      if (this.$route.meta) {
        this.$route.meta.title = title
      }
    },
    async loadCategories() {
      try {
        const response = await getAllCategories()
        this.categories = response.data || []
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
      }
    },

    async loadDishDetail() {
      try {
        const response = await getDishById(this.dishId)
        const dishData = response.data

        // 转换数据格式
        this.form = {
          name: dishData.name,
          categoryId: dishData.categoryId,
          price: dishData.price,
          description: dishData.description || '',
          image: dishData.image,
          code: dishData.code || '',
          flavors: dishData.flavors && dishData.flavors.length > 0
            ? dishData.flavors.map(flavor => {
              let tags = []
              try {
                if (flavor.value && flavor.value !== '[]') {
                  tags = JSON.parse(flavor.value)
                }
              } catch (e) {
                console.error('解析口味标签失败:', e)
              }
              return {
                ...flavor,
                tags: Array.isArray(tags) ? tags : [],
                tagInput: ''
              }
            })
            : [{ name: '', tags: [], tagInput: '' }]
        }
      } catch (error) {
        console.error('获取菜品详情失败:', error)
        this.$message.error('获取菜品详情失败')
      }
    },

    getImageUrl(imageName) {
      if (!imageName) return ''
      if (imageName.startsWith('http')) {
        return imageName
      }
      const baseUrl = process.env.VUE_APP_BASE_API || ''
      return `${baseUrl}/common/download?name=${imageName}`
    },

    // 口味名改变时加载对应的预设标签
    onFlavorNameChange(index) {
      const flavor = this.form.flavors[index]
      if (flavor.name) {
        const flavorOption = FLAVOR_OPTIONS.find(option => option.name === flavor.name)
        if (flavorOption) {
          // 保留用户已添加的标签，只添加预设中不存在的标签
          flavorOption.tags.forEach(tag => {
            if (!flavor.tags.includes(tag)) {
              flavor.tags.push(tag)
            }
          })
        }
      }
    },

    // 口味标签相关方法
    addFlavorTag(index) {
      const flavor = this.form.flavors[index]
      if (!flavor.tagInput.trim()) return

      if (!flavor.tags.includes(flavor.tagInput.trim())) {
        flavor.tags.push(flavor.tagInput.trim())
      }

      flavor.tagInput = ''
    },

    removeFlavorTag(flavorIndex, tagIndex) {
      const flavor = this.form.flavors[flavorIndex]
      flavor.tags.splice(tagIndex, 1)
    },

    addFlavor() {
      this.form.flavors.push({
        name: '',
        tags: [],
        tagInput: ''
      })
    },

    removeFlavor(index) {
      if (this.form.flavors.length > 1) {
        this.form.flavors.splice(index, 1)
      }
    },

    // 图片上传
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    },

    async handleImageUpload(options) {
      try {
        const formData = new FormData()
        formData.append('file', options.file)

        const response = await uploadFile(formData)
        if (response.code === 1) {
          this.form.image = response.data
          this.$message.success('图片上传成功')
        } else {
          this.$message.error('图片上传失败: ' + (response.msg || '未知错误'))
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$message.error('图片上传失败')
      }
    },

    // 准备提交数据
    prepareSubmitData() {
      const submitData = {
        name: this.form.name,
        categoryId: this.form.categoryId,
        price: this.form.price,
        description: this.form.description || '',
        image: this.form.image || '',
        code: this.form.code || '',
        status: 1,
        flavors: this.form.flavors
          .filter(flavor => flavor.name.trim() || flavor.tags.length > 0)
          .map(flavor => ({
            name: flavor.name,
            value: JSON.stringify(flavor.tags), // 将数组转换为JSON字符串
            showOption: flavor.showOption || false
          }))
      }

      // 设置为空数组
      if (submitData.flavors.length === 0) {
        submitData.flavors = []
      }

      return submitData
    },

    // 表单提交
    async submitForm(isContinue = false) {
      try {
        // 验证表单
        await this.$refs.dishForm.validate()

        this.loading = true

        // 准备提交数据
        const submitData = this.prepareSubmitData()
        console.log('提交的数据:', JSON.stringify(submitData, null, 2))

        let response
        if (this.isEdit) {
          submitData.id = this.dishId
          response = await updateDish(submitData)
          this.$message.success('修改菜品成功')
        } else {
          response = await addDish(submitData)
          this.$message.success('添加菜品成功')
        }

        console.log('服务器响应:', response)

        if (isContinue) {
          // 保存并继续添加，重置表单
          this.resetForm()
        } else {
          // 返回列表页
          this.$router.push('/menu/menu')
        }
      } catch (error) {
        console.error('保存菜品失败:', error)
        if (error.response) {
          console.error('服务器响应错误:', error.response.data)
          this.$message.error(`保存菜品失败: ${error.response.data.msg || '服务器错误'}`)
        } else {
          this.$message.error('保存菜品失败: ' + (error.message || '未知错误'))
        }
      } finally {
        this.loading = false
      }
    },

    handleSave() {
      this.submitForm(false)
    },

    handleSaveAndContinue() {
      this.submitForm(true)
    },

    resetForm() {
      this.form = {
        name: '',
        categoryId: '',
        price: null,
        description: '',
        image: '',
        code: '',
        flavors: [{ name: '', tags: [], tagInput: '' }] // 重置时保留一个空的口味配置
      }
      this.$refs.dishForm.clearValidate()
    },

    handleBack() {
      this.$router.push('/menu/menu')
    },

    handleCancel() {
      const message = this.isEdit ? '确定取消修改菜品吗？' : '确定取消添加菜品吗？'
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/menu/menu')
      })
    }
  }
}
</script>

<style scoped>
.add-menu-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 84px);
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header .title {
  font-size: 18px;
  font-weight: bold;
  margin-left: 16px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.form-row {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.form-item {
  flex: 1;
  margin-bottom: 0;
}

.price-unit {
  margin-left: 8px;
  color: #606266;
}

.flavor-section {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 16px;
  color: #606266;
}

.flavor-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.flavor-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.add-flavor-btn {
  margin-top: 8px;
}

.image-section {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
}

.avatar-uploader-icon:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon i {
  font-size: 28px;
  margin-bottom: 8px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 6px;
}

.description-section {
  margin-bottom: 32px;
}

.action-buttons {
  text-align: center;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.action-buttons .el-button {
  margin: 0 8px;
  min-width: 100px;
}
</style>
